package com.shundr;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.shundr.base.BaseActivity;
import com.shundr.common.CreateOrderActivity;
import com.shundr.common.FeedbackActivity;
import com.shundr.common.dao.RouteDao;
import com.shundr.common.dao.SyncDataDao;
import com.shundr.common.http.CommonRequest;
import com.shundr.common.model.SplashInfo;
import com.shundr.common.model.VersionInfo;
import com.shundr.common.util.ChangeColorIconWithText;
import com.shundr.common.util.JsonUtil;
import com.shundr.common.util.PrefConstants;
import com.shundr.common.util.PrefUtils;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.common.view.DialodUpdateApp;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.service.MessageConfig;
import com.shundr.frame.service.PhoneReceiver;
import com.shundr.frame.service.PhoneReceiver.PhoneHandler;
import com.shundr.frame.service.PushMessageReceiver;
import com.shundr.frame.service.PushMessageReceiver.ReceiverHandler;
import com.shundr.frame.service.ShundrService;
import com.shundr.frame.service.UpgradeService;
import com.shundr.frame.util.GetVersionUtil;
import com.shundr.frame.util.LLoader;
import com.shundr.frame.util.LLogger;
import com.shundr.order.OrderListActivity;
import com.shundr.route.RouteSettingActivity;
import com.shundr.route.http.RouteRequest;
import com.shundr.route.model.TruckerRouteInfo;
import com.shundr.user.LoginActivity;
import com.shundr.user.http.UserRequest;
import com.shundr.user.model.UserInfo;
import com.shundr.user.util.UserListener;
import com.shundr.user.util.UserUtil;
import com.umeng.soexample.commons.ShareUtil;

/**
 * 
 * MainActivity 主类
 * 
 * @author larry 2015-4-11 下午2:32:37 
 * @version 1.0.0
 *
 */
public class MainActivity extends BaseActivity implements OnClickListener,
		OnPageChangeListener,ReceiverHandler,UserListener,PhoneHandler{

	private LinearLayout mNetView;
	
	private ViewPager mViewPager;
	private List<Fragment> mTabs = new ArrayList<Fragment>();
	
	private SearchCargoFragment mSearchCargoFragment;
	private OftenRouteFragment mOftenRouteFragment;
	private UserInfoFragment mUserInfoFragment;
	private ToolFragment mToolFragment;
	
	private TextView tvDot_1;
	private TextView tvDot_2;
	private TextView tvDot_3;
	private TextView tvDot_4;
	
	private FragmentPagerAdapter mAdapter;
	
	private List<ChangeColorIconWithText> mTabIndicators = new ArrayList<ChangeColorIconWithText>();
	
	private RouteDao mRouteDao;
	private SyncDataDao mSyncDao;
	
	private Button btnSound;
	
	private Handler mHandler = new Handler(){

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UserRequest.LOGIN_SUCCESSED:
				try {
					String data = msg.obj.toString();
					JSONObject obj = new JSONObject(data);
					String accessToken = obj.getString("accessToken");
					UserInfo user = JsonUtil.fromJson(obj.getJSONObject("user").toString(), UserInfo.class);
					UserUtil.saveUserToLocal(mContext, user, accessToken);
					ToastHelper.toastShort(mContext, "登录成功");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case RouteRequest.GET_ROUTE_LIST_SUCCESSED:
				List<TruckerRouteInfo> routeList = (List<TruckerRouteInfo>)msg.obj;
				if(routeList!=null&&routeList.size()>0){
					mRouteDao.syncData(routeList);
				}
				break;
			case CommonRequest.GET_SPLASH_IMAGE_SUCCESSED:
				SplashInfo info = (SplashInfo)msg.obj;
				if(info != null){
					String time = info.getTime();
					mSyncDao.updateSyncByType(MessageConfig.SYNC_SPLASH, time);
					Intent intent=new Intent(mContext, UpgradeService.class);
					intent.putExtra("url", info.getUrl());
					intent.putExtra("flag", false);
					startService(intent);
				}
				break;
			case 100:
				initView();
				initDatas();
				mViewPager.setAdapter(mAdapter);
				initEvent();
				ProgressDialogHelper.dismiss();
				break;
			case CommonRequest.GET_APPSYS_INFO_UPDATE:
				VersionInfo version = (VersionInfo)msg.obj;
				if(version == null)
					return;
				DialodUpdateApp dialodUpdateApp=new DialodUpdateApp(mContext, version);
				dialodUpdateApp.show();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setDisplayHomeAsUpEnabled(false);
		this.setTitle("舜达天下");
		
		setContentView(R.layout.activity_main_new);
		PushMessageReceiver.mReceiverListeners.add(this);
		UserUtil.mUserListeners.add(this);
		PhoneReceiver.mPhoneListeners.add(this);
		LLoader.initUser(mContext);
		
		int index = getIntent().getIntExtra("index", 0);
		LLogger.e("index" , "index : " + index);
		
//		new UserRequest(mContext, mHandler).login("13237425260", "123456");
		//检查网络状态,提示去设置
		ShareUtil.init(this);
//		mHandler.sendEmptyMessage(100);
		initView();
		initDatas();
		mViewPager.setAdapter(mAdapter);
		initEvent();
		mRouteDao = new RouteDao();
		mSyncDao = new SyncDataDao();
		ProgressDialogHelper.dismiss();
		startService(new Intent(mContext, ShundrService.class));
		checkVersion();
		if(LContext.isLogin()){
			new RouteRequest(mContext, mHandler).getRouteList();
			new CommonRequest(mContext, new Handler()).saveAppOperate(1);
		}
//		new CommonRequest(this, mHandler).syncSplashImage(mSyncDao.getTimeByType(MessageConfig.SYNC_SPLASH));
	}
	
	/**
	 * 检查版本更新
	 */
	private void checkVersion(){	
		int VersionCode=GetVersionUtil.getVersionCode(getApplicationContext());
		int androidVersion = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
		new CommonRequest(mContext, mHandler).getAppSysInfo(VersionCode+"", androidVersion+"");
	}

	/**
	 * 初始化所有事件
	 */
	private void initEvent() {
		mViewPager.setOnPageChangeListener(this);
	}

	private void initDatas() {
		mSearchCargoFragment = new SearchCargoFragment();
		mUserInfoFragment = new UserInfoFragment();
		mOftenRouteFragment=new OftenRouteFragment();
		mToolFragment = new ToolFragment();
		mTabs.add(mSearchCargoFragment);
		mTabs.add(mOftenRouteFragment);
		mTabs.add(mUserInfoFragment);
		mTabs.add(mToolFragment);

		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

			@Override
			public int getCount() {
				return mTabs.size();
			}

			@Override
			public Fragment getItem(int position) {
				return mTabs.get(position);
			}
		};
	}

	private void initView() {
		mNetView = (LinearLayout)findViewById(R.id.net_status_bar_top);
		mNetView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startNetSetting();
			}
		});
		
		btnSound = (Button)findViewById(R.id.btn_sound);
		btnSound.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				boolean sound = PrefUtils.getPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
				if(sound){
					btnSound.setText("播报已关闭");
					PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_TTS_ON, false);
					LContext.isTtsOpened = false;
					btnSound.setBackgroundResource(R.drawable.circle_text_sound_close);
				}else{
					btnSound.setText("播报已开启");
					PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
					LContext.isTtsOpened = true;
					btnSound.setBackgroundResource(R.drawable.circle_text_sound_open);
				}
				
			}
		});
		
		mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
		mViewPager.setOffscreenPageLimit(4);

		ChangeColorIconWithText one = (ChangeColorIconWithText) findViewById(R.id.id_indicator_one);
		mTabIndicators.add(one);
		ChangeColorIconWithText two = (ChangeColorIconWithText) findViewById(R.id.id_indicator_two);
		mTabIndicators.add(two);
		ChangeColorIconWithText three = (ChangeColorIconWithText) findViewById(R.id.id_indicator_three);
		mTabIndicators.add(three);
		ChangeColorIconWithText four = (ChangeColorIconWithText) findViewById(R.id.id_indicator_four);
		mTabIndicators.add(four);
		
		tvDot_1 = (TextView)findViewById(R.id.tv_dot_1);
		tvDot_2 = (TextView)findViewById(R.id.tv_dot_2);
		tvDot_3 = (TextView)findViewById(R.id.tv_dot_3);
		tvDot_4 = (TextView)findViewById(R.id.tv_dot_4);
		
		if(PrefUtils.getPrefBoolean(mContext, PrefConstants.IV_DOT_4, true)){
			tvDot_4.setVisibility(View.VISIBLE);
			tvDot_4.setText("1");
		}

		one.setOnClickListener(this);
		two.setOnClickListener(this);
		three.setOnClickListener(this);
		four.setOnClickListener(this);

		one.setIconAlpha(1.0f);
	}

	@Override
	public void onResume() {
		super.onResume();
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				checkWallet();
			}
		}, 300);
		if(LContext.getCallLong(this) > 0 && LContext.isOrdered){
			onPhoned();
		}
		try {
			if(LContext.isLogin()){
				mOftenRouteFragment.checkSound();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void onDestroy() {
		PushMessageReceiver.mReceiverListeners.remove(this);
		UserUtil.mUserListeners.remove(this);
		PhoneReceiver.mPhoneListeners.remove(this);
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_overflow_main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			ToastHelper.toastShort(mContext, "欢迎使用舜达天下");
			break;
		case R.id.menu_add_route_often:
			if(LContext.isLogin()){
				startActivity(new Intent(mContext, RouteSettingActivity.class));
			}else{
				startActivity(new Intent(mContext, LoginActivity.class));
			}
			break;
		case R.id.menu_my_order:
			if(LContext.isLogin()){
				startActivity(new Intent(mContext, OrderListActivity.class));
			}else{
				startActivity(new Intent(mContext, LoginActivity.class));
			}
			break;
		case R.id.menu_help_feedback:
			startActivity(new Intent(mContext, FeedbackActivity.class));
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		clickTab(v);
	}

	/**
	 * 点击Tab按钮
	 * 
	 * @param v
	 */
	private void clickTab(View v) {
		resetOtherTabs();
		switch (v.getId()) {
		case R.id.id_indicator_one:
			mTabIndicators.get(0).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(0, false);
			tvDot_1.setVisibility(View.GONE);
			break;
		case R.id.id_indicator_two:
			mTabIndicators.get(1).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(1, false);
			tvDot_2.setVisibility(View.GONE);
			tvDot_2.setText("0");
			break;
		case R.id.id_indicator_three:
			mTabIndicators.get(2).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(2, false);
			tvDot_3.setVisibility(View.GONE);
			break;
		case R.id.id_indicator_four:
			mTabIndicators.get(3).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(3, false);
			tvDot_4.setVisibility(View.GONE);
			PrefUtils.setPrefBoolean(mContext, PrefConstants.IV_DOT_4, false);
			break;
		}
	}
	
	private void changeBottom(){
		if(mActionBar == null)
			return;
		switch (mViewPager.getCurrentItem()) {
		case 0:
			tvDot_1.setVisibility(View.GONE);
			break;
		case 1:
			tvDot_2.setVisibility(View.GONE);
			tvDot_2.setText("0");
			break;
		case 2:
			tvDot_3.setVisibility(View.GONE);
			break;
		case 3:
			tvDot_4.setVisibility(View.GONE);
			PrefUtils.setPrefBoolean(mContext, PrefConstants.IV_DOT_4, false);
			break;

		default:
			break;
		}
	}

	/**
	 * 重置其他的TabIndicator的颜色
	 */
	private void resetOtherTabs() {
		for (int i = 0; i < mTabIndicators.size(); i++) {
			mTabIndicators.get(i).setIconAlpha(0);
		}
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
		if (positionOffset > 0) {
			ChangeColorIconWithText left = mTabIndicators.get(position);
			ChangeColorIconWithText right = mTabIndicators.get(position + 1);
			left.setIconAlpha(1 - positionOffset);
			right.setIconAlpha(positionOffset);
		}
		changeBottom();
	}

	@Override
	public void onPageSelected(int position) {

	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}

	@Override
	public void onReceived(int type) {
		if(type == MessageConfig.CARGO){ 
			//显示点
			if(mViewPager.getCurrentItem() != 1){
				tvDot_2.setVisibility(View.VISIBLE);
				try {
					int num = Integer.parseInt(tvDot_2.getText().toString());
					num = num + 1;
					tvDot_2.setText(num + "");
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
		}else if(type == MessageConfig.ORDER){
			tvDot_3.setVisibility(View.VISIBLE);
		}
	}

	private long exitTime = 0;

	@Override
	public void onBackPressed() {
		if (mViewPager.getCurrentItem() != 0) {
			resetOtherTabs();
			mTabIndicators.get(0).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(0, false);
		} else {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				ToastHelper.toastShort(mContext, "再按一次退出舜达天下");
				exitTime = System.currentTimeMillis();
			} else {
				if(LContext.isLogin()){
					new CommonRequest(mContext, new Handler()).saveAppOperate(2);
				}
//				exitAPP();
				exitHome();
			}
		}
	}
	
	@Override
	public void onUserChanged(int flag) {
		LLogger.e("larry","登录 ：" + flag);
		if(flag == 0){//登录
			new RouteRequest(mContext, mHandler).getRouteList();
		}else if(flag == 1){//注销
//			btnLeft.setVisibility(View.GONE);
		}
	}

	@Override
	public void onPhoned() {
		startActivity(new Intent(mContext, CreateOrderActivity.class));
	}

	@Override
	public void onNetChange() {
		super.onNetChange();
		if(LContext.isNetworkConnected){
//			mNetView.setVisibility(View.GONE);
		}else{
//			mNetView.setVisibility(View.VISIBLE);
		}
	}

}
